package myJs

import myJs.myPkg.jquery._

import scala.scalajs.js.annotation._
import myPkg._
import Utils._

import scala.scalajs.js
import scalatags.Text.all._
import org.scalajs.dom.html.Element
import myJs.myPkg.bootstrap.Bootstrap.default._
import scalajs.js.JSConverters._
import Implicits._


@JSExportTopLevel("SickCase")
object SickCase {
  var index = 0
  var pathologyId = ""
  var name = ""
  var basic: js.Dictionary[js.Any] = _

  @JSExport("init")
  def init = {
    getBasic
    typeEvent
    bootStrapValidator

  }

  @JSExport("search")
  def search = {
    $("#content").hide()
    val bv = jQuery("#form").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().asInstanceOf[Boolean]
    if (valid) {
      index = layer.alert(element, layerOptions)
      pathologyId = $(":input[name='pathologyId']").`val`().toString
      name = $(":input[name='name']").`val`().toString
      showBasic
      layer.close(index)
    }

  }

  def typeEvent = {
    val rs = basic
    val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
    val typeData = array.map { x =>
      x.myGet("病理号")
    }
    g.$(":input[name='pathologyId']").typeahead(js.Dictionary("source" -> typeData))
  }

  @JSExport("showExample")
  def showExample(y: Element, name: String) = {
    val example = $(y).find("em").text().trim
    $(s":input[name='${name}']").`val`(example)
    g.$(s"#form").bootstrapValidator("revalidateField", name)
  }

  @JSExport("idBlur")
  def idBlur = {
    val rs = basic
    val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
    val row = array.filter { x =>
      x.myGet("病理号") == $(":input[name='pathologyId']").`val`().toString
    }.headOption
    if (row.isDefined) {
      val x = row.get
      $(":input[name='name']").`val`(x.myGet("姓名"))
    }

  }

  def showBasic = {
    $("#arms").hide()
    $("#bs68").hide()
    val rs = basic
    val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
    val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
    val row = array.filter { x =>
      x.myGet("病理号") == pathologyId && x.myGet("姓名") == name
    }.headOption
    if (row.isDefined) {
      val trueRow = row.get
      trueRow.foreach { case (key, v) =>
        $(s"p[id=${key}]").text(v.toString)
      }
      get10Gene
      getBraf
      getKnpb
      getLymSnp
      if (name == "张三" && pathologyId == "M19-0034") {
        $("#bs68").show()
        get68Snp
        get68Cnv
      }
      $("#content").show()
    } else {
      layer.close(index)
      Swal.swal(SwalOptions.title("错误").text("病理号或姓名错误！").`type`("error"))
      $("#content").hide()
    }

  }

  def getBasic = {
    val url = g.jsRoutes.controllers.SickCaseController.getBasic().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").async(false).success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      basic = rs
    }
    $.ajax(ajaxSettings)
  }

  def get10Gene = {
    val url = g.jsRoutes.controllers.SickCaseController.get10Gene().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.drop(7).map { columnName =>
        ColumnOptions.field(columnName).title(columnName).sortable(true).titleTooltip(columnName).
          field(columnName).titleTooltip(columnName)
      }
      val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
      val row = array.filter { x =>
        x.myGet("病理号") == pathologyId && x.myGet("姓名") == name
      }.headOption
      if (row.isDefined) {
        val options = TableOptions.data(rs("array")).columns(columns)
        $("#10GeneTable").bootstrapTable(options)
        $("#10Gene").show()
        $("#arms").show()
      } else {
        $("#10Gene").hide()
      }

    }
    $.ajax(ajaxSettings)
  }

  def getBraf = {
    val url = g.jsRoutes.controllers.SickCaseController.getBraf().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
      val row = array.filter { x =>
        x.myGet("病理号") == pathologyId && x.myGet("姓名") == name
      }.headOption
      if (row.isDefined) {
        val x = row.get
        $("#BRAF").text(x.myGet("BRAF"))
        $("#braf").show()
        $("#arms").show()
      } else {
        $("#braf").hide()
      }

    }
    $.ajax(ajaxSettings)
  }

  def getKnpb = {
    val url = g.jsRoutes.controllers.SickCaseController.getKnpb().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.drop(7).map { columnName =>
        ColumnOptions.field(columnName).title(columnName).sortable(true).titleTooltip(columnName).
          field(columnName).titleTooltip(columnName)
      }
      val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
      val row = array.filter { x =>
        x.myGet("病理号") == pathologyId && x.myGet("姓名") == name
      }.headOption
      if (row.isDefined) {
        val options = TableOptions.data(rs("array")).columns(columns)
        $("#knpbTable").bootstrapTable(options)
        $("#knpb").show()
        $("#arms").show()
      } else {
        $("#knpb").hide()
      }
    }
    $.ajax(ajaxSettings)
  }

  def getLymSnp = {
    val url = g.jsRoutes.controllers.SickCaseController.getLymSnp().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val trueColumnNames = (columnNames.drop(3).filterNot { x =>
        js.Array(columnNames(6), columnNames(7)).contains(x)
      }).toJSArray
      val columns = trueColumnNames.map { columnName =>
        ColumnOptions.field(columnName).title(columnName).sortable(true).titleTooltip(columnName).
          field(columnName).titleTooltip(columnName)
      }
      val parentStr = "lymSnp"
      val html = trueColumnNames.map { x =>
        label(marginRight := 15,
          input(`type` := "checkbox", checked, value := x, onclick := s"SickCase.setColumns('${x}','${parentStr}')", x)
        )
      }.mkString
      $(s"#${parentStr} #checkbox").html(html)
      val array = rs("array").asInstanceOf[js.Array[js.Dictionary[js.Any]]]
      val rows = array.filter { x =>
        x.myGet("病理号") == pathologyId && x.myGet("姓名") == name
      }
      if (rows.isEmpty) {
        $(s"#${parentStr}").hide()
      } else {
        val options = TableOptions.data(rows).columns(columns)
        $(s"#${parentStr} #table").bootstrapTable(options)
        trueColumnNames.drop(9).foreach { x =>
          $(s"#${parentStr} #table").bootstrapTable("hideColumn", x)
          $(s"input:checkbox[value='${x}']").attr("checked", false)
        }
        $(s"#${parentStr}").show()
      }


    }
    $.ajax(ajaxSettings)
  }

  def get68Snp = {
    val url = g.jsRoutes.controllers.SickCaseController.get68Snp().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val trueColumnNames = columnNames
      val columns = trueColumnNames.map { columnName =>
        js.Dictionary("field" -> columnName, "title" -> columnName, "sortable" -> true)
      }
      val parentStr = "68Snp"
      val html = trueColumnNames.map { x =>
        label(marginRight := 15,
          input(`type` := "checkbox", checked, value := x, onclick := s"SickCase.setColumns('${x}','${parentStr}')", x)
        )
      }.mkString
      $(s"#${parentStr} #checkbox").html(html)
      val dict = js.Dictionary("data" -> rs("array"), "columns" -> columns)
      g.$(s"#${parentStr} #table").bootstrapTable(dict)
      trueColumnNames.drop(9).foreach { x =>
        $(s"#${parentStr} #table").bootstrapTable("hideColumn", x)
        $(s"input:checkbox[value='${x}']").attr("checked", false)
      }
    }
    $.ajax(ajaxSettings)
  }

  def get68Cnv = {
    val url = g.jsRoutes.controllers.SickCaseController.get68Cnv().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val trueColumnNames = columnNames
      val columns = trueColumnNames.map { columnName =>
        js.Dictionary("field" -> columnName, "title" -> columnName, "sortable" -> true)
      }
      val parentStr = "68Cnv"
      val html = trueColumnNames.map { x =>
        label(marginRight := 15,
          input(`type` := "checkbox", checked, value := x, onclick := s"SickCase.setColumns('${x}','${parentStr}')", x)
        )
      }.mkString
      $(s"#${parentStr} #checkbox").html(html)
      val dict = js.Dictionary("data" -> rs("array"), "columns" -> columns)
      g.$(s"#${parentStr} #table").bootstrapTable(dict)
      trueColumnNames.drop(9).foreach { x =>
        $(s"#${parentStr} #table").bootstrapTable("hideColumn", x)
        $(s"input:checkbox[value='${x}']").attr("checked", false)
      }
    }
    $.ajax(ajaxSettings)
  }

  @JSExport("setColumns")
  def setColumns(value: String, parentStr: String) = {
    val element = $(s"input:checkbox[value='${value}']")
    if (element.is(":checked")) {
      $(s"#${parentStr} #table").bootstrapTable("showColumn", value)
    } else {
      $(s"#${parentStr} #table").bootstrapTable("hideColumn", value)
    }

  }

  @JSExport("bootStrapValidator")
  def bootStrapValidator = {
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "pathologyId" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "病理号不能为空！"
            )
          )
        ),
        "name" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "姓名不能为空！"
            )
          )
        ),

      )
    )
    g.$("#form").bootstrapValidator(dict)

  }


}
